package com.dream.testtubebaby_doctor.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.dream.testtubebaby_doctor.LookupImageActivity;
import com.dream.testtubebaby_doctor.R;
import com.dream.testtubebaby_doctor.adapter.WaitingRoomExpandableListAdapter;
import com.dream.testtubebaby_doctor.data.AddToldData;
import com.dream.testtubebaby_doctor.okhttp.OkHttpClientManager;
import com.dream.testtubebaby_doctor.utils.AppUtil;
import com.dream.testtubebaby_doctor.utils.ImageLoader;
import com.dream.testtubebaby_doctor.utils.LanguageUtils;
import com.dream.testtubebaby_doctor.utils.SharePreferencesManager;
import com.dream.testtubebaby_doctor.utils.ToastUtil;
import com.squareup.okhttp.Request;

public class WaitingRoomFragment extends Fragment {
	public static final String WAITING_ROOM_RECEIVER_ACTION = "waiting.room.receiver.action";
	private View rootView;
	// private TextView mSearchTextView;
	private EditText search_edit;
	// private List<AddToldData> groupData = new ArrayList<AddToldData>();
	private HashMap<String, List<AddToldData>> groupData = new HashMap<String, List<AddToldData>>();
	private WaitingRoomExpandableListAdapter waitingRoomExpandableListAdapter;
	private ExpandableListView expandableListView;
	private SharePreferencesManager mSharePreferencesManager;
	private WaitingRoomReveiver mWaitingRoomReveiver;
	private TextWatcher filterTextWatcher;
	protected int mScreenWidth;
	protected int mScreenHeight;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		DisplayMetrics metric = new DisplayMetrics();
		getActivity().getWindowManager().getDefaultDisplay().getMetrics(metric);
		mScreenWidth = metric.widthPixels;
		mScreenHeight = metric.heightPixels;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// initData();
		if (rootView == null) {
			rootView = inflater.inflate(R.layout.waiting_room_fragment, null);
			if (rootView != null) {
				mSharePreferencesManager = new SharePreferencesManager(
						getActivity());
				initView(rootView);
				initExpandableListView(rootView);
				mWaitingRoomReveiver = new WaitingRoomReveiver();
				IntentFilter filter = new IntentFilter();
				filter.addAction(WAITING_ROOM_RECEIVER_ACTION);
				getActivity().registerReceiver(mWaitingRoomReveiver, filter);
			}
		}
		ViewGroup parent = (ViewGroup) rootView.getParent();
		if (parent != null) {
			parent.removeView(rootView);
		}
		return rootView;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		getActivity().unregisterReceiver(mWaitingRoomReveiver);
	}

	private void initView(View view) {
		if (view == null) {
			return;
		}
		search_edit = (EditText) view.findViewById(R.id.search_edit);
		filterTextWatcher = new TextWatcher() {
			public void afterTextChanged(Editable editable) {
			}

			public void beforeTextChanged(CharSequence charsequence, int i,
					int j, int k) {
			}

			public void onTextChanged(CharSequence charsequence, int i, int j,
					int k) {
				if (waitingRoomExpandableListAdapter != null)
					waitingRoomExpandableListAdapter.getFilter().filter(
							charsequence);
			}

		};
		search_edit.addTextChangedListener(filterTextWatcher);
	}

	private void initExpandableListView(View view) {
		if (view == null) {
			return;
		}
		waitingRoomExpandableListAdapter = new WaitingRoomExpandableListAdapter(
				getActivity().getApplicationContext(), groupData);
		expandableListView = (ExpandableListView) view.findViewById(R.id.list);
		expandableListView.setAdapter(waitingRoomExpandableListAdapter);
		expandableListView.setGroupIndicator(null);
		expandableListView
				.setOnGroupExpandListener(new OnGroupExpandListener() {

					@Override
					public void onGroupExpand(int groupPosition) {
						for (int i = 0; i < groupData.size(); i++) {
							if (groupPosition != i) {
								expandableListView.collapseGroup(i);
							}
						}
					}

				});
		expandableListView.setOnChildClickListener(new OnChildClickListener() {
			
			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				AddToldData addToldData = groupData.get(groupData.keySet().toArray()[groupPosition]).get(childPosition);
				String stepname = addToldData.getStepname();
				if (stepname.equals(getResources().getStringArray(
						R.array.told_project_array)[2])) {// bchao
					showBchaoPopWindow(v, addToldData);
				} else if (stepname.equals(getResources()
						.getStringArray(R.array.told_project_array)[3])) {// yanxue
					showYanxuePopWindow(v, addToldData);
				}
				return false;
			}
		});
	}

	private int leftruanViewIds[] = { R.id.l_ruan_val_1, R.id.l_ruan_val_2,
			R.id.l_ruan_val_3, R.id.l_ruan_val_4, R.id.l_ruan_val_5,
			R.id.l_ruan_val_6, R.id.l_ruan_val_7, R.id.l_ruan_val_8 };
	private int rightruanViewIds[] = { R.id.r_ruan_val_1, R.id.r_ruan_val_2,
			R.id.r_ruan_val_3, R.id.r_ruan_val_4, R.id.r_ruan_val_5,
			R.id.r_ruan_val_6, R.id.r_ruan_val_7, R.id.r_ruan_val_8 };
	private int jsViewIds[] = { R.id.js_value_1, R.id.js_value_2,
			R.id.js_value_3, R.id.js_value_4, R.id.js_value_5, R.id.js_value_6 };
	
	private void showBchaoPopWindow(View v, AddToldData addToldData) {
		View view = getActivity().getLayoutInflater().inflate(R.layout.waiting_room_list_child_bchao,
				null);
		TextView leftOvaryTextArray[] = new TextView[8];
		TextView rightOvaryTextArray[] = new TextView[8];
		String[] leftOvaryValues = addToldData.getLeftovary().split(";");
		String[] rightOvaryValues = addToldData.getRightovary().split(";");

		for (int i = 0; i < 8; i++) {
			leftOvaryTextArray[i] = (TextView) view
					.findViewById(leftruanViewIds[i]);
			rightOvaryTextArray[i] = (TextView) view
					.findViewById(rightruanViewIds[i]);
			if (i < leftOvaryValues.length) {
				leftOvaryTextArray[i].setText(leftOvaryValues[i]);
			}
			if (i < rightOvaryValues.length) {
				rightOvaryTextArray[i].setText(rightOvaryValues[i]);
			}
		}
		if (addToldData.getAttach() != null) {
			addPopImage(view, addToldData);
		}
		if(!TextUtils.isEmpty(addToldData.getFeedback())){
			TextView bchao_feedback = (TextView)view.findViewById(R.id.bchao_feedback);
			bchao_feedback.setText(addToldData.getFeedback());
		}
		final PopupWindow popupWindow = new PopupWindow(getActivity());
		popupWindow.setContentView(view);
		popupWindow.setWidth(mScreenWidth);
		popupWindow.setHeight(mScreenWidth / 2);
		popupWindow.setOutsideTouchable(true);
		popupWindow.setFocusable(true);
//		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		popupWindow.showAsDropDown(v);
//		popupWindow.showAtLocation(v, Gravity.CENTER_HORIZONTAL, 0, 0);
	}

	private void showYanxuePopWindow(View v, AddToldData addToldData) {
		View view = getActivity().getLayoutInflater().inflate(
				R.layout.waiting_room_list_child_yanxue, null);
		TextView jsViewArray[] = new TextView[6];
		String jsValues[] = addToldData.getBlood().split(";");
		for (int i = 0; i < 6; i++) {
			jsViewArray[i] = (TextView) view.findViewById(jsViewIds[i]);
			if (i < jsValues.length) {
				jsViewArray[i].setText(jsValues[i]);
			}
		}
		if (addToldData.getAttach() != null) {
			addPopImage(view, addToldData);
		}
		if(!TextUtils.isEmpty(addToldData.getFeedback())){
			TextView bchao_feedback = (TextView)view.findViewById(R.id.yanxue_feedback);
			bchao_feedback.setText(addToldData.getFeedback());
		}
		final PopupWindow popupWindow = new PopupWindow(getActivity());
		popupWindow.setContentView(view);
		popupWindow.setWidth(mScreenWidth);
		popupWindow.setHeight(mScreenWidth / 2);
		popupWindow.setOutsideTouchable(true);
		popupWindow.setFocusable(true);
//		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		popupWindow.showAsDropDown(v);
	}

	private void addPopImage(View view, AddToldData addToldData) {
		LinearLayout wait_bchao_image_l = (LinearLayout) view
				.findViewById(R.id.wait_bchao_image_l);
		String imagesurl[] = addToldData.getAttach();
		wait_bchao_image_l.removeAllViews();
		for (int i = 0; i < imagesurl.length; i++) {
			final String url = imagesurl[i];
			ImageView imageView = new ImageView(getActivity());
			imageView.setLayoutParams(new LinearLayout.LayoutParams(200, 200));
			imageView.setScaleType(ScaleType.FIT_CENTER);
			imageView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					startLookUpImage(url);
				}
			});

			ImageLoader.getInstance().loadNetWorkImage(
					AppUtil.getCompletePhotoUrl(url), imageView);
			wait_bchao_image_l.addView(imageView);
		}
	}

	private void startLookUpImage(String url) {
		try {
			Intent intent = new Intent("com.intent.action.lookup.image");
			intent.putExtra(LookupImageActivity.LOOKUP_IMAGE_PATH_KEY,
					AppUtil.getCompletePhotoUrl(url));
			intent.putExtra(LookupImageActivity.LOOKUP_IMAGE_TYPE,
					LookupImageActivity.NETWORK_IMAGE);
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intent);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	

	@Override
	public void onStart() {
		super.onStart();
		updateFinishedAdviceList();
	}

	private void updateFinishedAdviceList() {
		HashMap<String, String> params = new HashMap<String, String>();
		params.put("doctorid",
				String.valueOf(mSharePreferencesManager.readUserId()));
		OkHttpClientManager.postAsyn(OkHttpClientManager.BASEURL
				+ "m=Home&c=App&a=Dct_getfinishedadvice",
				new OkHttpClientManager.ResultCallback<String>() {

					@Override
					public void onError(Request request, Exception e) {
						ToastUtil.toast(getActivity(), R.string.server_error);
					}

					@Override
					public void onResponse(String response) {
						// {"id":"17","userid":"6","fromtime":"2015-9-24","totime":"2015-9-27","steptypeid":"0","stepname":"\u9a8c\u8840","drug":"\u8fbe\u83f2\u6797","howmuch":"0.05mg",
						// "f_finished":"2","finishtime":0,"attach":["121.40.78.46\/tb\/imageDctAdvice\/a.jpg","121.40.78.46\/tb\/imageDctAdvice\/b.jpg"],"username":"wuliqing1"}
						try {
							JSONObject obj = new JSONObject(response);
							if (obj != null) {
								int result = obj.getInt("result");
								if (result == 0) {
									groupData.clear();
									JSONArray jsonMessage = new JSONArray(obj
											.getString("finishedadvices"));
									for (int i = 0; i < jsonMessage.length(); i++) {
										JSONObject jsonObject = (JSONObject) jsonMessage
												.get(i);
										AddToldData addToldData = AddToldData
												.getAddToldListNode(jsonObject);
										addToldData.setStepname(LanguageUtils
												.getToldProjectWithCode(
														getActivity(),
														addToldData
																.getStepname()));
										addToldData.setDrug(LanguageUtils
												.getInjectionMedicineStringWithCode(
														getActivity(),
														addToldData.getDrug()));
										addToldData.setHowmuch(LanguageUtils
												.getQuantitieStringWithCode(
														getActivity(),
														addToldData
																.getHowmuch()));
										if (groupData.containsKey(addToldData
												.getUsername())) {
											groupData.get(
													addToldData.getUsername())
													.add(addToldData);
										} else {
											List<AddToldData> addToldDatas = new ArrayList<AddToldData>();
											addToldDatas.add(addToldData);
											groupData.put(
													addToldData.getUsername(),
													addToldDatas);
										}
									}
									waitingRoomExpandableListAdapter
											.notifyDataSetChanged();
								}
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				}, params);
	}

	private class WaitingRoomReveiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals("WAITING_ROOM_RECEIVER_ACTION")) {
				updateFinishedAdviceList();
			}
		}

	}
}
